//
//  VerCodeViewController.m
//  location
//
//  Created by Dongxiang Xu on 2025/5/16.
//

#import "VerCodeViewController.h"
#import "RegisterConfigViewController.h"
#import "XDXBaseTabBarViewController.h"
#import "WXApi.h"

@interface VerCodeViewController ()

@property (nonatomic,strong) UITextField *textField;
@property (nonatomic,strong) UIButton *timeButton;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,assign) CGFloat angle;
@property (nonatomic,strong) NSTimer *loginTimer;
@property (nonatomic,strong) UIImageView *logining;
@property (nonatomic,strong) UILabel *noReceive;
@property (nonatomic,assign) NSInteger errorCount;

@end

@implementation VerCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = WhiteColor;
    [self initView];
    [self initTimer];
}

- (void)initView
{
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, STATUSHEIGHT+16, SCREEN_WIDTH, 26)];
    title.font = REAL_MEDIUM_FONT(17);
    title.textAlignment = NSTextAlignmentCenter;
    title.textColor = RealBlackColor;
    title.text = @"输入验证码";
    [self.view addSubview:title];
    
    UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, title.maxY+19, SCREEN_WIDTH, 24)];
    subTitle.font = DEFAULT_FONT(13);
    subTitle.textAlignment = NSTextAlignmentCenter;
    subTitle.textColor = GraryTooHeavyColor;
    subTitle.text = [NSString stringWithFormat:@"验证码已经发送到尾号 %@ 的手机",[self.phonenumber substringFromIndex:7]];
    [self.view addSubview:subTitle];
    
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(2*SCREEN_WIDTH, 0, 100, 10)];
    _textField.keyboardType = UIKeyboardTypeNumberPad;
    [_textField becomeFirstResponder];
    _textField.tintColor = BlackColor;
    [_textField addTarget:self action:@selector(textChangeEvent:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_textField];
    
    for (int i=0; i<4; i++) {
        UIButton *view = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-198)/2+i*52, CGRectGetMaxY(subTitle.frame)+70, 42, 56)];
        view.layer.masksToBounds = YES;
        if (i==0) {
            view.backgroundColor = NormalMainColor;
        }else{
            view.backgroundColor = RealWhiteColor;
        }
        [view.layer setCornerRadius:16];
        [view setTitleColor:RealBlackColor forState:UIControlStateNormal];
        [view.titleLabel setFont:RUBIK_BOLD_FONT(24)];
        view.tag = 100 + i;
        [self.view addSubview:view];
        [[view rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self.textField becomeFirstResponder];
        }];
    }
    
    _timeButton = [[UIButton alloc] initWithFrame:CGRectMake(30, CGRectGetMaxY(subTitle.frame)+152, SCREEN_WIDTH-60, 18)];
    [_timeButton setTitleColor:GraryHeavyLightColor forState:UIControlStateNormal];
    [_timeButton.titleLabel setFont:DEFAULT_FONT(13)];
    _timeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.timeButton setTitle:@"60秒后可以请求新验证码" forState:UIControlStateNormal];
    [self.view addSubview:_timeButton];
    [[_timeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if ([self.timeButton.titleLabel.text containsString:@"重新发送"]) {
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [param setValue:self.phonenumber forKey:@"phonenumber"];
            CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
            [manager encryptedPOST:@"/auth/smslogin"
            parameters:param
            success:^(NSDictionary *responseObject) {
                if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                    [self initTimer];
                }else{
                    [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                }
            }
            failure:^(NSError *aError) {
               
            }];
        }
    }];
    
    _logining = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-16)/2, _timeButton.maxY+70, 16, 16)];
    _logining.image = [UIImage imageNamed:@"logining"];
    _logining.hidden = YES;
    [self.view addSubview:_logining];
    
    _noReceive = [[UILabel alloc] initWithFrame:CGRectMake(41, _timeButton.maxY+26, SCREEN_WIDTH-82, 18)];
    _noReceive.userInteractionEnabled = YES;
    _noReceive.font = REAL_MEDIUM_FONT(14);
    _noReceive.textColor = GraryLightColor;
    _noReceive.textAlignment = NSTextAlignmentCenter;
    _noReceive.hidden = YES;
    NSString *string = @"无法收到？联系客服";
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:string];
    [str addAttribute:NSForegroundColorAttributeName value:NormalMainColor range:NSMakeRange(5, string.length-5)];
    _noReceive.attributedText = str;
    [self.view addSubview:_noReceive];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        WXOpenCustomerServiceReq *req = [[WXOpenCustomerServiceReq alloc] init];
        req.corpid = @"wwd398f4f09a46d09b";    //企业ID
        req.url = @"https://work.weixin.qq.com/kfid/kfcf5c99c0434b5983c";            //客服URL
        [WXApi sendReq:req completion:^(BOOL success) {
            
        }];
    }];
    [_noReceive addGestureRecognizer:tap];
}

- (void)initTimer
{
    [self.timer invalidate];
    self.timer = nil;
    __block NSInteger seconds = 60;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        seconds = seconds-1;
        if (seconds<=0) {
            self.errorCount = self.errorCount+1;
            if (self.errorCount>=3) {
                self.noReceive.hidden = NO;
            }
            [timer invalidate];
            timer = nil;
            [self.timeButton setImage:[UIImage imageNamed:@"loging"] forState:UIControlStateNormal];
            [self.timeButton setTitle:@" 重新发送" forState:UIControlStateNormal];
            [self.timeButton setTitleColor:GraryHeavyLightColor forState:UIControlStateNormal];
            [self.timeButton.titleLabel setFont:REAL_MEDIUM_FONT(14)];
        }else{
            [self.timeButton setImage:nil forState:UIControlStateNormal];
            [self.timeButton setTitleColor:GraryTooHeavyColor forState:UIControlStateNormal];
            [self.timeButton setTitle:[NSString stringWithFormat:@"%ld秒后可以请求新验证码",(long)seconds] forState:UIControlStateNormal];
            [self.timeButton.titleLabel setFont:DEFAULT_FONT(13)];
        }
    }];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

- (void)textChangeEvent:(UITextField *)textField
{
    if (_textField.text.length>=4) {
        _textField.text = [_textField.text substringToIndex:4];
        [((UIButton *)[self.view viewWithTag:103]) setTitle:[_textField.text substringWithRange:NSMakeRange(3, 1)] forState:UIControlStateNormal];
        [self.view viewWithTag:103].backgroundColor = NormalMainColor;
        [((UIButton *)[self.view viewWithTag:103]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:102]) setTitle:[_textField.text substringWithRange:NSMakeRange(2, 1)] forState:UIControlStateNormal];
        [self.view viewWithTag:102].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:102]) setTitleColor:NormalMainColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:101]) setTitle:[_textField.text substringWithRange:NSMakeRange(1, 1)] forState:UIControlStateNormal];
        [self.view viewWithTag:101].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:101]) setTitleColor:NormalMainColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:100]) setTitle:[_textField.text substringWithRange:NSMakeRange(0, 1)] forState:UIControlStateNormal];
        [self.view viewWithTag:100].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:100]) setTitleColor:NormalMainColor forState:UIControlStateNormal];

        [self loginEvent];
    }else if (_textField.text.length == 3){
        [((UIButton *)[self.view viewWithTag:103]) setTitle:@"" forState:UIControlStateNormal];
        [self.view viewWithTag:103].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:103]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:102]) setTitle:[_textField.text substringWithRange:NSMakeRange(2, 1)] forState:UIControlStateNormal];
        [self.view viewWithTag:102].backgroundColor = NormalMainColor;
        [((UIButton *)[self.view viewWithTag:102]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:101]) setTitle:[_textField.text substringWithRange:NSMakeRange(1, 1)] forState:UIControlStateNormal];
        [self.view viewWithTag:101].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:101]) setTitleColor:NormalMainColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:100]) setTitle:[_textField.text substringWithRange:NSMakeRange(0, 1)] forState:UIControlStateNormal];
        [self.view viewWithTag:100].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:100]) setTitleColor:NormalMainColor forState:UIControlStateNormal];
    }else if (_textField.text.length == 2){
        [((UIButton *)[self.view viewWithTag:103]) setTitle:@"" forState:UIControlStateNormal];
        [self.view viewWithTag:103].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:103]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:102]) setTitle:@"" forState:UIControlStateNormal];
        [self.view viewWithTag:102].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:102]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:101]) setTitle:[_textField.text substringWithRange:NSMakeRange(1, 1)] forState:UIControlStateNormal];
        [self.view viewWithTag:101].backgroundColor = NormalMainColor;
        [((UIButton *)[self.view viewWithTag:101]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:100]) setTitle:[_textField.text substringWithRange:NSMakeRange(0, 1)] forState:UIControlStateNormal];
        [self.view viewWithTag:100].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:100]) setTitleColor:NormalMainColor forState:UIControlStateNormal];
    }else if (_textField.text.length == 1){
        [((UIButton *)[self.view viewWithTag:103]) setTitle:@"" forState:UIControlStateNormal];
        [self.view viewWithTag:103].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:103]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:102]) setTitle:@"" forState:UIControlStateNormal];
        [self.view viewWithTag:102].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:102]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:101]) setTitle:@"" forState:UIControlStateNormal];
        [self.view viewWithTag:101].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:101]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:100]) setTitle:[_textField.text substringWithRange:NSMakeRange(0, 1)] forState:UIControlStateNormal];
        [self.view viewWithTag:100].backgroundColor = NormalMainColor;
        [((UIButton *)[self.view viewWithTag:100]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
    }else{
        [((UIButton *)[self.view viewWithTag:103]) setTitle:@"" forState:UIControlStateNormal];
        [self.view viewWithTag:103].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:103]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:102]) setTitle:@"" forState:UIControlStateNormal];
        [self.view viewWithTag:102].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:102]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:101]) setTitle:@"" forState:UIControlStateNormal];
        [self.view viewWithTag:101].backgroundColor = RealWhiteColor;
        [((UIButton *)[self.view viewWithTag:101]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        
        [((UIButton *)[self.view viewWithTag:100]) setTitle:@"" forState:UIControlStateNormal];
        [self.view viewWithTag:100].backgroundColor = NormalMainColor;
        [((UIButton *)[self.view viewWithTag:100]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
    }
}

- (void)loginEvent
{
    if (_textField.text.length==4) {
        [_textField setEnabled:NO];
        _logining.hidden = NO;
        self.loginTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 repeats:YES block:^(NSTimer * _Nonnull timer) {
            self.angle = self.angle + 0.03;
            self.logining.transform = CGAffineTransformMakeRotation(self.angle);
            if (self.angle>1.0) {        
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                [param setValue:self.textField.text forKey:@"code"];
                [param setValue:self.phonenumber forKey:@"phonenumber"];
                CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                [manager encryptedPOST:@"/auth/smsloginvalidate"
                parameters:param
                success:^(NSDictionary *responseObject) {
                    if ([responseObject[@"code"] integerValue]==200) {
                        [XDXShareInstance shareInstance].access_token = responseObject[@"data"][@"access_token"];
                        [[NSUserDefaults standardUserDefaults] setValue:responseObject[@"data"][@"access_token"] forKey:AccessToken];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        
                        if ([responseObject[@"data"][@"loginStatus"] isEqualToString:@"login"]) {
                            XDXBaseTabBarViewController *tb = [[XDXBaseTabBarViewController alloc] init];
                            [UIApplication sharedApplication].keyWindow.rootViewController = tb;
                            [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
                        }else{
                            RegisterConfigViewController *vc = [[RegisterConfigViewController alloc] init];
                            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
                            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
                            [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
                        }
                        
                    }else{
                        self.errorCount = self.errorCount+1;
                        if (self.errorCount>=3) {
                            self.noReceive.hidden = NO;
                        }
                        [[HCToast shareInstance] showToast:responseObject[@"msg"]];
                    }
                    [self.textField setEnabled:YES];
                    self.logining.hidden = YES;
                }
                failure:^(NSError *aError) {
                    [self.textField setEnabled:YES];
                    self.logining.hidden = YES;
                }];                
                [self.loginTimer invalidate];
                self.loginTimer = nil;
            }
        }];
        [[NSRunLoop currentRunLoop] addTimer:self.loginTimer forMode:NSRunLoopCommonModes];
    }
}

@end
